package com.ysxm.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	@ExceptionHandler(CustomException.class)
	public ResponseInfo<String> undefinedResponseException(Exception e) {
		ResponseInfo<String> responseInfo = new ResponseInfo<String>(ResponseInfo.ERROR_CODE, e.getMessage());
		return responseInfo;
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResponseInfo<Object> paramCheckExceptionHandler(MethodArgumentNotValidException e) {
		return new ResponseInfo<Object>(ResponseInfo.ERROR_CODE, "参数错误", getErrors(e.getBindingResult()));
	}

	private Map<String, Object> getErrors(BindingResult result) {
		Map<String, Object> map = new HashMap<>();
		List<FieldError> list = result.getFieldErrors();
		for (FieldError error : list) {
			map.put(error.getField(), error.getDefaultMessage());
		}
		return map;
	}
}
